// 渲染进程中的蓝牙服务 - 使用Web Bluetooth API
class BluetoothManager {
  constructor() {
    this.device = null;
    this.server = null;
    this.service = null;
    this.characteristic = null;
    this.isConnected = false;
    this.eventCallbacks = {};
    
    // 按摩椅设备特征 (需要根据实际设备调整)
    this.MASSAGE_CHAIR_SERVICE_UUID = 0xFFF0;
    this.MASSAGE_CHAIR_CHARACTERISTIC_UUID = 0xFFF1;
    
    // 设备过滤器
    this.deviceFilters = [
      { namePrefix: '按摩椅' },
      { namePrefix: 'MassageChair' },
      { namePrefix: 'MASSAGE' },
      { services: [this.MASSAGE_CHAIR_SERVICE_UUID] }
    ];
  }

  // 事件监听器管理
  on(event, callback) {
    if (!this.eventCallbacks[event]) {
      this.eventCallbacks[event] = [];
    }
    this.eventCallbacks[event].push(callback);
  }

  emit(event, data) {
    if (this.eventCallbacks[event]) {
      this.eventCallbacks[event].forEach(callback => callback(data));
    }
  }

  async initialize() {
    try {
      // 检查浏览器是否支持Web Bluetooth
      if (!navigator.bluetooth) {
        throw new Error('此浏览器不支持Web Bluetooth API');
      }
      
      // 检查蓝牙是否可用
      const available = await navigator.bluetooth.getAvailability();
      if (!available) {
        throw new Error('蓝牙不可用，请确保蓝牙已开启');
      }
      
      console.log('Web Bluetooth API 初始化成功');
      return true;
    } catch (error) {
      console.error('Web Bluetooth 初始化失败:', error);
      throw error;
    }
  }

  async startScanning(timeout = 10000) {
    try {
      await this.initialize();
      
      console.log('开始扫描按摩椅设备...');
      
      // 使用 requestDevice 来扫描和选择设备
      const device = await navigator.bluetooth.requestDevice({
        filters: this.deviceFilters,
        optionalServices: [this.MASSAGE_CHAIR_SERVICE_UUID]
      });

      if (device) {
        const deviceInfo = {
          id: device.id,
          name: device.name || '未知设备',
          device: device
        };
        
        console.log('发现按摩椅设备:', deviceInfo.name, deviceInfo.id);
        return [deviceInfo]; // 返回设备数组格式以保持兼容性
      }
      
      return [];
    } catch (error) {
      if (error.name === 'NotFoundError') {
        console.log('用户取消了设备选择');
        return [];
      }
      throw new Error(`扫描失败: ${error.message}`);
    }
  }

  async connectToDevice(deviceInfo) {
    try {
      this.device = deviceInfo.device || deviceInfo;

      console.log('连接设备:', this.device.name);

      // 连接到GATT服务器
      this.server = await this.device.gatt.connect();
      console.log('GATT服务器连接成功');

      // 获取主要服务
      this.service = await this.server.getPrimaryService(this.MASSAGE_CHAIR_SERVICE_UUID);
      console.log('获取服务成功');

      // 获取特征
      this.characteristic = await this.service.getCharacteristic(this.MASSAGE_CHAIR_CHARACTERISTIC_UUID);
      console.log('获取特征成功');

      // 启用通知
      await this.characteristic.startNotifications();
      this.characteristic.addEventListener('characteristicvaluechanged', (event) => {
        this.handleDataReceived(event);
      });

      // 监听设备断开连接
      this.device.addEventListener('gattserverdisconnected', () => {
        console.log('设备已断开连接');
        this.handleDisconnection();
      });

      this.isConnected = true;
      this.emit('connectionStateChanged', 'connected');
      
      console.log('按摩椅设备连接并配置完成');
      return true;

    } catch (error) {
      this.handleDisconnection();
      throw new Error(`连接失败: ${error.message}`);
    }
  }

  async disconnect() {
    try {
      if (this.device && this.device.gatt.connected) {
        await this.device.gatt.disconnect();
      }
      this.handleDisconnection();
      console.log('设备断开连接成功');
    } catch (error) {
      console.error('断开连接时出错:', error);
      this.handleDisconnection();
      throw new Error(`断开连接失败: ${error.message}`);
    }
  }

  handleDisconnection() {
    this.isConnected = false;
    this.device = null;
    this.server = null;
    this.service = null;
    this.characteristic = null;
    this.emit('connectionStateChanged', 'disconnected');
  }

  async handleDataReceived(event) {
    try {
      const value = event.target.value;
      const dataArray = new Uint8Array(value.buffer);
      
      console.log('接收到数据:', Array.from(dataArray).map(b => b.toString(16).padStart(2, '0')).join(' '));
      
      // 使用主进程的协议解析器解析数据
      const result = await window.electronAPI.protocol.parseData(Array.from(dataArray));
      
      if (result.success) {
        this.emit('dataReceived', result.data);
      } else {
        console.error('数据解析失败:', result.error);
      }
    } catch (error) {
      console.error('处理接收数据时出错:', error);
    }
  }

  async sendCommand(commandBuffer) {
    try {
      if (!this.isConnected || !this.characteristic) {
        throw new Error('设备未连接');
      }

      console.log('发送指令:', Array.from(commandBuffer).map(b => b.toString(16).padStart(2, '0')).join(' '));
      
      await this.characteristic.writeValue(new Uint8Array(commandBuffer));
      console.log('指令发送成功');
      return true;

    } catch (error) {
      throw new Error(`发送指令失败: ${error.message}`);
    }
  }

  isDeviceConnected() {
    return this.isConnected;
  }
}

// 导出给全局使用
window.bluetoothManager = new BluetoothManager();